﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Windows.Forms;

public partial class frmDiagnosis: BaseLoginFrom
{

	Diagnosis diagnosis;

    public frmDiagnosis()
    {    	
        InitializeComponent();
        new frmDrugsHelper(txtDrugs);
        if (diagnosis != null && diagnosis.Status != 1)
        {
            btOK.Enabled = false;
        }
        new TextBoxBindMonthCalendar(this.txtBirthDay);
    }

    public frmDiagnosis(string DiagnosisId)
        : this(Diagnosis.Single(DiagnosisId))
    { }

    public frmDiagnosis(Diagnosis dg)
        : this()
    {
        diagnosis = dg;
        if (dg != null)
        {
            if (dg.Patient != null)
            {
                txtUserName.Text = dg.Patient.UserName;
                txtTelephone.Text = dg.Patient.Telephone;
                txtEmail.Text = dg.Patient.Email;
                txtBodyProperty.Text = dg.Patient.BodyProperty;
                txtBirthDay.Text = dg.Patient.BirthDay;
                txtPeople.Text = dg.Patient.People;
                chkSex.Checked = dg.Patient.Sex == 1;
            }
            txtProperty_Ask.Text = dg.Property_Ask;
            txtProperty_Listent.Text = dg.Property_Listen;
            txtProperty_Look.Text = dg.Property_Look;
            txtProperty_Thouch.Text = dg.Property_Touch;
            txtRemarks.Text = dg.Remarks;
            txtReseaon.Text = dg.Reseaon;
            txtMassage.Text = dg.Massage;
            bool Drugs = true;
            if (dg.Drugs != null)
                foreach (string i in dg.Drugs)
                {
                    if (Drugs)
                        Drugs = false;
                    else
                        txtDrugs.AppendText(" ");
                    txtDrugs.AppendText(i);
                }
        }
    }

    private void btOK_Click(object sender, EventArgs e)
    {
        Save();
        this.Close();
    }

    void Save()
    {
        if (diagnosis == null || string.IsNullOrEmpty(diagnosis.Id))
        {
            diagnosis = new Diagnosis
            {
                DoctorId = ApplictionData.CurrentUser.UserId,
                Patient = new UserExtense
                {
                    UserId = (diagnosis == null || string.IsNullOrEmpty(diagnosis.PatientId)) ? string.Empty : diagnosis.PatientId,
                    UserName = txtUserName.Text,
                    BirthDay = txtBirthDay.Text,
                    CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    BodyProperty = txtBodyProperty.Text,
                    Email = txtEmail.Text,
                    Status = 1,
                    Sex = chkSex.Checked ? 1 : -1,
                    Telephone = txtTelephone.Text,
                    People = txtPeople.Text,
                },
                Property_Ask = txtProperty_Ask.Text,
                Property_Listen = txtProperty_Listent.Text,
                Property_Look = txtProperty_Look.Text,
                Property_Touch = txtProperty_Thouch.Text,
                Drugs = new string[] { txtDrugs.Text },
                CreateDay = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Reseaon = txtReseaon.Text,
                Remarks = txtRemarks.Text,
                Massage = txtMassage.Text,
            };
            diagnosis.Insert();
        }
        else
        {
            diagnosis.Id = diagnosis.Id;
            diagnosis.DoctorId = ApplictionData.CurrentUser.UserId;
            diagnosis.Patient = new UserExtense
            {
                UserId = diagnosis.Patient.UserId,
                UserName = txtUserName.Text,
                BirthDay = txtBirthDay.Text,
                CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                BodyProperty = txtBodyProperty.Text,
                Email = txtEmail.Text,
                Status = 1,
                Sex = chkSex.Checked ? 1 : -1,
                Telephone = txtTelephone.Text,
            };
            diagnosis.Property_Ask = txtProperty_Ask.Text;
            diagnosis.Property_Listen = txtProperty_Listent.Text;
            diagnosis.Property_Look = txtProperty_Look.Text;
            diagnosis.Property_Touch = txtProperty_Thouch.Text;
            diagnosis.Reseaon = txtReseaon.Text;
            diagnosis.Remarks = txtRemarks.Text;
            diagnosis.Drugs = new string[] { txtDrugs.Text };
            diagnosis.Massage = txtMassage.Text;
            diagnosis.Update();
        }
    }

    private void mcd_DateSelected(object sender, DateRangeEventArgs e)
    {
        txtBirthDay.Text = e.Start.ToString("yyyy-MM-dd 00:00:00");
        ((Control)sender).Visible = false;
    }

    private void txtBirthDay_Click(object sender, EventArgs e)
    {
    }

    private void txtBirthDay_Enter(object sender, EventArgs e)
    {

    }
    
    private void btPrint_Click(object sender, EventArgs e)
    {
        if (diagnosis == null)
        {
            if (MessageBox.Show("为保存不能打印，是否保存？", "确定", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Save();
            }
            else
            {
                return;
            }
        }
        if (printDialog.ShowDialog(this) != DialogResult.OK)
            return;

        if (printDialog.Document == null)
        {
            printDialog.Document = new System.Drawing.Printing.PrintDocument();
            printDialog.Document.PrintPage += new PrintPageEventHandler(Document_PrintPage);
        }
        try
        {
            printDialog.Document.Print();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
	
    void Document_PrintPage(object sender,PaintEventArgs e){
    	Document_PrintPage(e.Graphics);
    }
    
    void Document_PrintPage(object sender, PrintPageEventArgs e)
    {
    	
    	Document_PrintPage(e.Graphics);
    	return;
    	
        Bitmap img = new Bitmap(665, 1024);
        Graphics g =
            //e.Graphics;
          Graphics.FromImage(img);
        //Font font = new Font("宋体", 12, FontStyle.Regular);
        //SolidBrush pen = new SolidBrush(Color.Black);
        //g.DrawString(diagnosis.CreateDate, font, pen, new Point(452, 6));
        //g.DrawString(diagnosis.Patient.UserName, font, pen, new PointF(48, 48));
        //g.DrawString(diagnosis.Patient.Sex == 1 ? "男" : "女", font, pen, new PointF(175, 48));
        //g.DrawString(DateTime.Now.ToString("yyyy年MM月dd日"), font, pen, new PointF(511, 48));
        //g.DrawString(diagnosis.Property_Ask, font, pen, new PointF(6, 120));

        g.DrawImage(global::HealthExa.Properties.Resources.Print, new Point(0, 0));

        Font fontLabel = new Font("宋体", 14, FontStyle.Bold);
        Font fontText = new Font("宋体", 12, FontStyle.Regular);
        SolidBrush brush = new SolidBrush(Color.Black);

        PointF p;//= new PointF(0, 0);

        g.DrawString(diagnosis.Patient.Telephone, fontText, brush, new PointF(425, 14));
        g.DrawString(diagnosis.Patient.UserName, fontText, brush, new PointF(25, 49));
        g.DrawString(diagnosis.Patient.Sex == 1 ? "男" : "女", fontText, brush, new PointF(152, 49));
        g.DrawString(diagnosis.Patient.People, fontText, brush, new PointF(275, 49));
        if (!string.IsNullOrEmpty(diagnosis.Patient.BirthDay))
        {
            DateTime dt;
            if (DateTime.TryParse(diagnosis.Patient.BirthDay, out dt))
                g.DrawString((DateTime.Now.Year - dt.Year).ToString(), fontText, brush, new PointF(400, 49));
        }
        g.DrawString(DateTime.Now.ToString("yyyy年MM月dd日"), fontText, brush, new PointF(528, 49));




        p = new PointF(17, 66);
        //652-------635
        //来诊原因：
        //问诊：
        //脉诊：
        //望診：
        //诊断：
        //内调：
        //推拿：
        //备注：
        p = FormatString("来诊原因：", fontLabel, brush, diagnosis.Reseaon, fontText, brush, 635, g, p);

        //73;
        p.Y = 138;
        p = FormatString("问诊：", fontLabel, brush, diagnosis.Property_Ask, fontText, brush, 635, g, p);

        p.Y = 211;
        p = FormatString("脉诊：", fontLabel, brush, diagnosis.Property_Touch, fontText, brush, 635, g, p);

        p.Y = 284;
        p = FormatString("望診：", fontLabel, brush, diagnosis.Property_Look, fontText, brush, 635, g, p);

        p.Y = 357;
        p = FormatString("诊断：", fontLabel, brush, diagnosis.Property_Listen, fontText, brush, 635, g, p);

        foreach (string d in diagnosis.Drugs)
        {
            p.Y = 430;
            p = FormatString("内调：", fontLabel, brush, d, fontText, brush, 635, g, p);
        }

        p.Y = 504;
        p = FormatString("推拿：", fontLabel, brush, diagnosis.Massage, fontText, brush, 635, g, p);

        p.Y = 577;
        p = FormatString("备注：", fontLabel, brush, diagnosis.Remarks, fontText, brush, 635, g, p);


        //foreach (Control i in this.Controls)
        //{
        //    Label lb = i as Label;
        //    if (i == txtBirthDay)
        //    {
        //        DateTime dt;
        //        if (DateTime.TryParse(txtBirthDay.Text, out dt))
        //        {
        //            g.DrawString((DateTime.Now.Year - dt.Year).ToString(), i.Font, new SolidBrush(lb.ForeColor), new PointF(this.Padding.Left + i.Left, this.Padding.Top + i.Top));
        //        }
        //        break;
        //    }
        //    if (lb != null)
        //    {
        //        g.DrawString(lb.Text, lb.Font, new SolidBrush(lb.ForeColor), new PointF(this.Padding.Left + i.Left, this.Padding.Top + i.Top));
        //        break;
        //    }
        //    TextBox tb = i as TextBox;
        //    if (tb != null)
        //    {
        //        g.DrawString(tb.Text, tb.Font, new SolidBrush(tb.ForeColor), new PointF(this.Padding.Left + i.Left, this.Padding.Top + i.Top));
        //        break;
        //    }
        //}
        img.Save("index.bmp");
    }
    
    void Document_PrintPage(Graphics g){
    	g.TranslateTransform(90,60);
    	float DocumentHeight=1000;
    	float DocumentWidth=600;
    	float DocumentPadding=3;
    	Font fontLabel=new Font("宋体",14f, FontStyle.Bold);
    	Font fontText=new Font("宋体",12f,FontStyle.Regular);
    	
    	SolidBrush brushLabel=new SolidBrush(Color.Black);
    	SolidBrush brushText=new SolidBrush(Color.Black);
    	
    	Matrix mt;
    	DateTime dt;
    	
    	Pen penBorder=new Pen(Color.Black);
    	
    	
    	
    	g.DrawRectangle(penBorder,0,0,DocumentWidth,DocumentHeight);
    	
    	const string MeasureChar=" ";
    	
    	float LineHeight=Math.Max(g.MeasureString(MeasureChar,fontLabel).Height,g.MeasureString(MeasureChar,fontText).Height)+DocumentPadding*2;
    	float LineJudgHeight=Math.Abs(g.MeasureString(MeasureChar,fontLabel).Height-g.MeasureString(MeasureChar,fontText).Height);
    	
    	g.DrawString("康芝堂中医调理会馆",fontLabel,brushLabel,DocumentPadding,DocumentPadding);
    	g.DrawString("电话:",fontLabel,brushLabel,DocumentPadding+DocumentWidth*3/5,DocumentPadding);
    	g.DrawString(diagnosis.Patient.Telephone,fontText,brushText,DocumentPadding+DocumentWidth*3/5+g.MeasureString("电话:",fontText).Width,DocumentPadding+LineJudgHeight);
    	
    	g.TranslateTransform(0,LineHeight);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
    	g.DrawString("姓名",fontLabel,brushLabel,DocumentPadding+DocumentWidth/5*0,DocumentPadding);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*1,0,DocumentWidth/5*1,LineHeight);
    	
    	g.DrawString("性别",fontLabel,brushLabel,DocumentPadding+DocumentWidth/5*1,DocumentPadding);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*2,0,DocumentWidth/5*2,LineHeight);
    	
    	g.DrawString("名族",fontLabel,brushLabel,DocumentPadding+DocumentWidth/5*2,DocumentPadding);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*3,0,DocumentWidth/5*3,LineHeight);
    
    	g.DrawString("年龄",fontLabel,brushLabel,DocumentPadding+DocumentWidth/5*3,DocumentPadding);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*4,0,DocumentWidth/5*4,LineHeight);
    	
    	g.DrawString("来诊日期",fontLabel,brushLabel,DocumentPadding+DocumentWidth/5*4,DocumentPadding);
    	
    	g.TranslateTransform(0,LineHeight);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
    	g.DrawString(diagnosis.Patient.UserName,fontText,brushText,DocumentPadding+DocumentWidth/5*0,DocumentPadding+LineJudgHeight);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*1,0,DocumentWidth/5*1,LineHeight);
    	
    	g.DrawString(diagnosis.Patient.Sex==1?"男":"女",fontText,brushText,DocumentPadding+DocumentWidth/5*1,DocumentPadding+LineJudgHeight);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*2,0,DocumentWidth/5*2,LineHeight);
    	
    	g.DrawString(diagnosis.Patient.People,fontText,brushText,DocumentPadding+DocumentWidth/5*2,DocumentPadding+LineJudgHeight);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*3,0,DocumentWidth/5*3,LineHeight);
    
    	if(DateTime.TryParse(diagnosis.Patient.BirthDay,out dt))
    		g.DrawString((DateTime.Now.Year-dt.Year).ToString(),fontText,brushText,DocumentPadding+DocumentWidth/5*3,DocumentPadding+LineJudgHeight);
    	
    	g.DrawLine(penBorder,DocumentWidth/5*4,0,DocumentWidth/5*4,LineHeight);
    	
    	if(diagnosis.CreateDate!=null && diagnosis.CreateDate.Length>0 && DateTime.TryParse(diagnosis.CreateDate,out dt)){
    	   	g.DrawString(dt.ToString("yyyy年MM月dd日"),fontText,brushText,DocumentPadding+DocumentWidth/5*4,DocumentPadding+LineJudgHeight);
    	}
    	g.TranslateTransform(0,LineHeight);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
//
//：
//：
//：
//：
//：
//：
//：
		FormatString(g,"来诊原因：",fontLabel,brushLabel,diagnosis.Reseaon,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);    	
    	g.TranslateTransform(0,LineHeight*3);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
		FormatString(g,"问诊：",fontLabel,brushLabel,diagnosis.Property_Ask,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	g.TranslateTransform(0,LineHeight*10);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
		FormatString(g,"脉诊：",fontLabel,brushLabel,diagnosis.Property_Touch,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	g.TranslateTransform(0,LineHeight*2);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
		FormatString(g,"望診：",fontLabel,brushLabel,diagnosis.Property_Look,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	g.TranslateTransform(0,LineHeight*3);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
		FormatString(g,"诊断：",fontLabel,brushLabel,diagnosis.Property_Listen,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	g.TranslateTransform(0,LineHeight*3);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
    	if(diagnosis.Drugs!=null && diagnosis.Drugs.Length>0)
    	foreach(string i in diagnosis.Drugs){
    		FormatString(g,"内调：",fontLabel,brushLabel,i,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	}
    	g.TranslateTransform(0,LineHeight*7);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
		FormatString(g,"推拿：",fontLabel,brushLabel,diagnosis.Massage,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	g.TranslateTransform(0,LineHeight*3);
    	g.DrawLine(penBorder,0,0,DocumentWidth,0);
    	
		FormatString(g,"备注：",fontLabel,brushLabel,diagnosis.Remarks,fontText,brushText,DocumentWidth,DocumentPadding,LineHeight,LineJudgHeight);
    	
    	
    	
		
    }
    
    void FormatString(Graphics g, string strLabel,Font fontLabel,SolidBrush brushLabel,string strText,Font fontText,SolidBrush brushText,float documentWidth,float documentPadding,float documentLineHeight,float documentLineJudg){
    	//Queue<char> qu=new Queue<char>(strLabel);
    	StringBuilder sb=new StringBuilder();
    	
    	g.DrawString(strLabel,fontLabel,brushLabel,documentPadding,documentPadding);
    	SizeF sfLabel=g.MeasureString(strLabel,fontLabel);
     	float x=sfLabel.Width,y=0;
     	x=0;y=sfLabel.Height;
	   	Queue<char> qu=new Queue<char>(strText);
	   	
	   	while(qu.Count>0){
	   		char i=qu.Dequeue();
    		if(g.MeasureString(sb.ToString()+i.ToString(),fontText).Width+documentPadding*2+sfLabel.Width>documentWidth){
    			g.DrawString(sb.ToString(),fontText,brushText,x,y+documentPadding+documentLineJudg);
    			sb=new StringBuilder().Append(i);
    			x=0;
    			y+=documentLineHeight;
    			break;
    		}
    		sb.Append(i);
    	}
	   	while(qu.Count>0){
	   		char i=qu.Dequeue();
	   		if(g.MeasureString(sb.ToString()+i.ToString(),fontText).Width+documentPadding*2>documentWidth){
    			g.DrawString(sb.ToString(),fontText,brushText,x+documentPadding,y+documentPadding+documentLineJudg);
    			x=0;
    			y+=documentLineHeight;
    			sb=new StringBuilder();
	   		}
	   		sb.Append(i);
	   	}
	   	if(sb!=null && sb.Length>0){
    		g.DrawString(sb.ToString(),fontText,brushText,x+documentPadding,y+documentPadding+documentLineJudg);
	   	}
    }

    PointF FormatString(string strLabel, Font fontLabel, SolidBrush brushLabel, string strText, Font fontText, SolidBrush brushText, int width, Graphics g, PointF p)
    {
        PointF ps = p;
        SizeF ms = g.MeasureString(strLabel, fontLabel);
        //p = new PointF(p.X + ms.Width, p.Y + ms.Height);
        //g.DrawString(strLabel, fontLabel, brushLabel, p);
        StringBuilder sb = new StringBuilder();

        bool FirstLine = true;


        foreach (char i in strLabel)
        {
            if (p.X + g.MeasureString(sb.ToString() + i.ToString(), fontText).Width > width)
            {
                if (FirstLine)
                {
                    FirstLine = false;
                    //g.DrawString(sb.ToString(), fontText, brushText, p);
                    p = new PointF(17, p.Y + g.MeasureString(sb.ToString(), fontText).Height);
                    sb = new StringBuilder();
                }
                else
                {
                    sb.Append(System.Environment.NewLine);
                    sb.Append(i);
                }
                break;
            }
            else
            {
                sb.Append(i);
            }
        }
        g.DrawString(sb.ToString(), fontLabel, brushLabel, p);
        if (FirstLine)
        {
            p = new PointF(p.X + g.MeasureString(sb.ToString(), fontLabel).Width, p.Y + 1);
        }
        sb = new StringBuilder();
        foreach (char i in strText)
        {
            if (p.X - 17 + g.MeasureString(sb.ToString() + i.ToString(), fontText).Width > width)
            {
                if (FirstLine)
                {
                    FirstLine = false;
                    g.DrawString(sb.ToString(), fontText, brushText, p);
                    p = new PointF(17, p.Y + g.MeasureString(" ", fontText).Height + 1);
                    sb = new StringBuilder();
                }
                else
                {
                    sb.Append(System.Environment.NewLine);
                    sb.Append(i);
                }
            }
            else
            {
                sb.Append(i);
            }
        }
        g.DrawString(sb.ToString(), fontText, brushText, p);
        //g.DrawLine(new Pen(brushText), ps, new PointF(652, p.Y));

        p = new PointF(17, p.Y + g.MeasureString(" ", fontText).Height + 1);
        //g.DrawLine(new Pen(brushText), ps, new PointF(ps.X, p.Y));
        //g.DrawLine(new Pen(brushText), new PointF(652, ps.Y), new PointF(652, p.Y));
        //g.DrawLine(new Pen(brushLabel), p, new PointF(652, p.Y));
        return p;
    }

    string AddNewLine(string Source, Graphics g, Font font, int Width)
    {
        StringBuilder sb = new StringBuilder();
        foreach (char i in Source)
        {
            SizeF s = g.MeasureString(sb.ToString(), font);
            sb.Append(i);
            if (s.Width > Width)
            {
                sb.Remove(sb.Length - 1, 1);
                sb.Append(System.Environment.NewLine);
                sb.Append(i);
            }
        }
        return sb.ToString();
    }

    private void txtDrugs_Click(object sender, EventArgs e)
    {
        //txtDrugsHelper = new frmDrugsHelper(txtDrugs);
        //AddMdiParent(txtDrugsHelper);
    }

    //private void btPrint_Click(object sender, EventArgs e)
    //{
    //    //打印预览
    //    //PrintPreviewDialog ppd = new PrintPreviewDialog();
    //    PrintDocument pd = new PrintDocument();
    //    //设置边距
    //    Margins margin = new Margins(20, 20, 20, 20);
    //    pd.DefaultPageSettings.Margins = margin;
    //    ////纸张设置默认
    //    //PaperSize pageSize = new PaperSize("First custom size", 800, 600);
    //    //pd.DefaultPageSettings.PaperSize = pageSize;
    //    //打印事件设置
    //    pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
    //    //ppd.Document = pd;
    //    //ppd.ShowDialog();
    //    try
    //    {
    //        pd.Print();
    //    }
    //    catch (Exception ex)
    //    {
    //        MessageBox.Show(ex.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
    //        pd.PrintController.OnEndPrint(pd, new PrintEventArgs());
    //    }
    //}

    void PrintWindow(Control c, Graphics g)
    {
        if (c == null || !c.Visible || g == null)
        {
            return;
        }
        if (c.Region != null)
            g.FillRegion(new SolidBrush(c.BackColor), c.Region);
        else
            g.FillRectangle(new SolidBrush(c.BackColor), new Rectangle(c.Location, c.Size));
        if (c.Text != null && c.Text.Length > 0)
        {
            g.DrawString(c.Text, c.Font, new SolidBrush(c.ForeColor), c.Location);
        }
        if (c.Controls != null && c.Controls.Count > 0)
        {
            g.TranslateTransform(c.Left, c.Top);
            foreach (Control i in c.Controls)
            {
                PrintWindow(i, g);
            }
            g.TranslateTransform(-c.Left, -c.Top);
        }
    }
}